#include <string>
#include <fstream>
#include <GL/gl.h>
#include <GL/glu.h>
#include <SRL/Utils/Core.h>
#include <SRL/Utils/Vector.h>
#include <SRL/Utils/Matrix.h>
#include <SRL/Utils/Extensions.h>
#include <SRL/Engine/Texture.h>
#include <SRL/Engine/FrameBuffer.h>
#include <SRL/Engine/Program.h>
#include <SRL/Engine/Shader.h>
#include <SRL/Engine/ScreenMap.h>

namespace srl {
    
    ScreenMap::ScreenMap(int px, int py, int pw, int ph) {
        x = px;
        y = py;
        w = pw;
        h = ph;
    }
    void ScreenMap::Viewport(int px, int py, int pw, int ph) {
        x = px;
        y = py;
        w = pw;
        h = ph;
    }
    void ScreenMap::LinkProgram(Program *prg) {
    	if(prg == NULL)
    		SRL_Except("The ScreenMap program cannot be NULL");
        mPrg = prg;
    }
    void ScreenMap::LinkFBO(FrameBuffer *fbo) {
    	if(fbo == NULL)
    		SRL_Except("The ScreenMap FBO cannot be NULL");
    	mFbo = fbo;
    }
    void ScreenMap::Render() {
    	GLint vp[4];
		glGetIntegerv(GL_VIEWPORT, vp);
		x = vp[0];
        y = vp[1];
        w = vp[2];
        h = vp[3];
    
        // Prepare rendering
        glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		glOrtho( -w/2, w/2, -h/2, h/2, 000, 50000.0);
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		glClear (GL_DEPTH_BUFFER_BIT );
	    glViewport( x, y, w, h);
	    glEnable(GL_TEXTURE_2D);

	    //Render
	    mPrg->Use();
	    	//mPrg->Uniform("srlTexture", mFbo, 0);
	    	mPrg->Uniform("srlTexture0", mFbo->GetTex(0), 0);
	        glBegin(GL_TRIANGLE_STRIP);
	            glTexCoord2f(0,0);
	            glVertex2f(-w/2,-h/2);

				glTexCoord2f(1,0);
				glVertex2f(w/2,-h/2);

				glTexCoord2f(0,1);
				glVertex2f(-w/2,h/2);

				glTexCoord2f(1,1);
				glVertex2f(w/2,h/2);	
	        glEnd();
	    srl::Program::DUse();
    }
};
